<template>
	<view class="spc-xr-chart">
		<!-- 均值图 -->
		<qiun-data-charts ref="meanChart" type="line" :opts="meanChartOpts" :ontouch="true" onzoom
			:chartData="meanChartData" @getIndex="onMeanChartIndex"></qiun-data-charts>

		<!-- 极差图 -->
		<qiun-data-charts style="margin-top: 20px;" ref="rangeChart" type="line" :opts="rangeChartOpts" :ontouch="true" onzoom
			:chartData="rangeChartData" @getIndex="onRangeChartIndex"></qiun-data-charts>
	</view>
</template>

<script>
	export default {
		name: "SpcXRChart",
		props: {
			data: {
				type: Array,
				required: true
			},
			spec: {
				type: Object,
				default: () => ({
					usl: null,
					lsl: null,
					target: null
				})
			}
		},
		data() {
			return {
				meanChartData: {},
				rangeChartData: {},
				meanChartOpts: {
					legend: {},
					xAxis: {
						disableGrid: true
					},
					yAxis: {}, // 会在 processData 中动态生成
					extra: {
						line: {
							type: "straight",
							animation: true,
							disableLegend: false
						},
						markLine: { // 标记线配置
							data: [] // 会在 processData 中动态生成
						}
					}
				},
				rangeChartOpts: {
					legend: {},
					xAxis: {
						disableGrid: true
					},
					yAxis: {}, // 会在 processData 中动态生成
					extra: {
						line: {
							type: "straight",
							animation: true,
							disableLegend: false
						},
						markLine: { // 标记线配置
							data: [] // 会在 processData 中动态生成
						}
					}
				}
			};
		},
		watch: {
			data: {
				handler(newVal) {
					this.processData(newVal);
				},
				immediate: true
			}
		},
		methods: {
			processData(data) {
				if (!data || data.length === 0) return;

				const xLabels = data.map((item, index) => index + 1);
				const meanValues = data.map(item => item.mean);
				const rangeValues = data.map(item => item.range);

				// 1. 计算控制限
				const meanControlLimits = this.calculateControlLimits(meanValues);
				const rangeControlLimits = this.calculateRangeControlLimits(rangeValues);

				// 2. 计算均值图Y轴范围（严格使用USL/LSL作为边界）
				const meanYAxisOptions = this.calculateMeanYAxisOptions(meanValues, this.spec);

				// 3. 计算极差图Y轴范围（保持原有逻辑，从0开始）
				const rangeYAxisOptions = this.calculateRangeYAxisOptions(rangeValues);

				// 4. 构建均值图数据
				this.meanChartData = {
					categories: xLabels,
					series: [{
						name: "均值",
						data: meanValues,
						color: "#1890FF"
					}]
				};

				// 5. 配置均值图标记线
				const meanMarkLines = [{
						value: meanControlLimits.ucl.toFixed(3),
						labelText: 'UCL=' + meanControlLimits.ucl.toFixed(3),
						showLabel: true,
						labelAlign: 'right',
						lineColor: '#f56c6c',
						labelFontColor: '#f56c6c',
						labelBgOpacity: 0
					},
					{
						value: meanControlLimits.cl.toFixed(3),
						labelText: 'CL=' + meanControlLimits.cl.toFixed(3),
						showLabel: true,
						labelAlign: 'right',
						lineColor: '#f56c6c',
						labelFontColor: '#f56c6c',
						labelBgOpacity: 0
					},
					{
						value: meanControlLimits.lcl.toFixed(3),
						labelText: 'LCL=' + meanControlLimits.lcl.toFixed(3),
						showLabel: true,
						labelAlign: 'right',
						lineColor: '#f56c6c',
						labelFontColor: '#f56c6c',
						labelBgOpacity: 0
					}
				];

				// 如果有USL/LSL/Target，添加到标记线
				if (this.spec.usl !== null) {
					meanMarkLines.push({
						labelText: 'USL=' + this.spec.usl.toFixed(3),
						value: this.spec.usl.toFixed(3),
						showLabel: true,
						labelAlign: 'right',
						lineColor: '#3fc314',
						labelFontColor: '#3fc314',
						labelBgOpacity: 0
					});
				}

				if (this.spec.lsl !== null) {
					meanMarkLines.push({
						labelText: 'LSL=' + this.spec.lsl.toFixed(3),
						value: this.spec.lsl.toFixed(3),
						showLabel: true,
						labelAlign: 'right',
						lineColor: '#3fc314',
						labelFontColor: '#3fc314',
						labelBgOpacity: 0
					});
				}

				if (this.spec.target !== null) {
					meanMarkLines.push({
						labelText: 'Target=' + this.spec.target.toFixed(3),
						value: this.spec.target.toFixed(3),
						showLabel: true,
						labelAlign: 'right',
						lineColor: '#3fc314',
						labelFontColor: '#3fc314',
						labelBgOpacity: 0
					});
				}

				// 更新均值图配置
				this.meanChartOpts = {
					padding: [20, 80, 0, 0],
					legend: {
						show: false
					},
					xAxis: {
						disableGrid: true
					},
					yAxis: meanYAxisOptions,
					extra: {
						line: {
							type: "straight",
							animation: true,
							disableLegend: false
						},
						markLine: {
							type: "dash",
							data: meanMarkLines
						}
					}
				};

				// 6. 构建极差图数据
				this.rangeChartData = {
					categories: xLabels,
					series: [{
						name: "极差",
						data: rangeValues,
						color: "#1890FF"
					}]
				};

				// 7. 配置极差图标记线
				this.rangeChartOpts = {
					padding: [20, 80, 0, 0],
					legend: {
						show: false
					},
					xAxis: {
						disableGrid: true
					},
					yAxis: rangeYAxisOptions,
					extra: {
						line: {
							type: "straight",
							animation: true,
							disableLegend: false
						},
						markLine: {
							type: 'dash',
							data: [{
									value: rangeControlLimits.ucl.toFixed(3),
									labelText: 'UCL=' + rangeControlLimits.ucl.toFixed(3),
									showLabel: true,
									labelAlign: 'right',
									lineColor: '#f56c6c',
									labelFontColor: '#f56c6c',
									labelBgOpacity: 0
								},
								{
									value: rangeControlLimits.cl.toFixed(3),
									labelText: 'CL=' + rangeControlLimits.cl.toFixed(3),
									showLabel: true,
									labelAlign: 'right',
									lineColor: '#f56c6c',
									labelFontColor: '#f56c6c',
									labelBgOpacity: 0
								},
								{
									value: Math.max(0, rangeControlLimits.lcl).toFixed(3),
									labelText: 'LCL=' + Math.max(0, rangeControlLimits.lcl).toFixed(3),
									showLabel: true,
									labelAlign: 'right',
									lineColor: '#f56c6c',
									labelFontColor: '#f56c6c',
									labelBgOpacity: 0
								}
							]
						}
					}
				};
			},

			// 计算控制限
			calculateControlLimits(values) {
				const mean = values.reduce((sum, val) => sum + val, 0) / values.length;
				const stdDev = Math.sqrt(
					values.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / values.length
				);

				return {
					ucl: mean + 3 * stdDev, // 上控制限
					cl: mean, // 中心线
					lcl: mean - 3 * stdDev // 下控制限
				};
			},

			// 计算极差控制限
			calculateRangeControlLimits(rangeValues) {
				const mean = rangeValues.reduce((sum, val) => sum + val, 0) / rangeValues.length;
				const stdDev = Math.sqrt(
					rangeValues.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / rangeValues.length
				);

				// 确保LCL不小于0
				return {
					ucl: mean + 3 * stdDev, // 上控制限
					cl: mean, // 中心线
					lcl: Math.max(0, mean - 3 * stdDev) // 下控制限（不小于0）
				};
			},

			// 计算均值图Y轴范围（严格使用USL/LSL作为边界）
			calculateMeanYAxisOptions(values, spec) {
				// 使用USL/LSL作为Y轴边界（如果有）
				let yMin = spec.lsl !== null ? spec.lsl : null;
				let yMax = spec.usl !== null ? spec.usl : null;

				// 如果没有USL/LSL，使用统计方法计算
				if (yMin === null || yMax === null) {
					const mean = values.reduce((sum, val) => sum + val, 0) / values.length;
					const variance = values.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / values.length;
					const stdDev = Math.sqrt(variance);

					// 计算合理的Y轴范围（使用3-sigma原则）
					if (yMin === null) yMin = mean - 3 * stdDev;
					if (yMax === null) yMax = mean + 3 * stdDev;

					// 确保Y轴范围不会太窄
					const minRange = stdDev * 2;
					if (yMax - yMin < minRange) {
						const padding = (minRange - (yMax - yMin)) / 2;
						yMin = yMin - padding;
						yMax = yMax + padding;
					}

					// 确保Y轴起点不为负数（如果数据都是正数）
					if (yMin < 0 && Math.min(...values) >= 0) {
						yMin = 0;
					}
				}

				// 格式化显示精度
				return {
					format: val => val.toFixed(3),
					data: [{
						min: +yMin.toFixed(3),
						max: +yMax.toFixed(3),
						tofix: 2
					}]
				};
			},

			// 计算极差图Y轴范围（保持原有逻辑）
			calculateRangeYAxisOptions(values) {
				// 计算基本统计量
				const mean = values.reduce((sum, val) => sum + val, 0) / values.length;
				const variance = values.reduce((sum, val) => sum + Math.pow(val - mean, 2), 0) / values.length;
				const stdDev = Math.sqrt(variance);

				// 计算合理的Y轴范围（使用3-sigma原则，从0开始）
				let yMax = mean + 3 * stdDev;

				// 确保Y轴范围不会太窄
				const minRange = stdDev * 2;
				if (yMax < minRange) {
					yMax = minRange;
				}

				// 格式化显示精度
				return {
					format: val => val.toFixed(3),
					data: [{
						min: 0,
						max: +yMax.toFixed(3),
						tofix: 2
					}]
				};
			},

			onMeanChartIndex(e) {
				const index = e.currentIndex.index;
				// if (typeof index === "number") {
				//     this.$refs.rangeChart.showToolTip(index);
				// }
			},
			onRangeChartIndex(e) {
				const index = e.currentIndex.index;
				// if (typeof index === "number") {
				//     this.$refs.meanChart.showToolTip(index);
				// }
			}
		}
	};
</script>

<style scoped>
	.spc-xr-chart {
		display: flex;
		flex-direction: column;
		padding: 20rpx;
	}

	qiun-data-charts {
		margin-bottom: 40rpx;
		background: #fff;
		border-radius: 16rpx;
		box-shadow: 0 4rpx 10rpx rgba(0, 0, 0, 0.05);
	}
</style>